package com.soul.common.utils;

import com.soul.common.bean.comm.TreeVo;
import com.soul.common.fun.TreeFunction;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

public class TreeUtil {

    public static <T extends TreeVo<T>> List<T> buildTree(List<T> trees,Long rootId){
        List<T> treeVos = new ArrayList<>();
        if (ObjectUtils.isEmpty(trees)){
            return treeVos;
        }
        trees.forEach(t->{
            if (Objects.equals(t.getParentId(),rootId)){
                List<T> ts = buildTree(trees, t.getId());
                t.setChildren(ts);
                treeVos.add(t);
            }
        });
        return treeVos;
    }

    public static <T extends TreeVo<T>> void forEach(List<T> trees, TreeFunction<T> function){
        __forEach(trees,null,function);
    }
    public static <T extends TreeVo<T>> void forEach(List<T> trees, Consumer<T> function){
        if (ObjectUtils.isEmpty(trees)){
            return ;
        }
        trees.forEach(t->{
            function.accept(t);
            List<T> children = t.getChildren();
            forEach(children,function);
        });
    }
    private static  <T extends TreeVo<T>> void __forEach(List<T> trees, T parent ,TreeFunction<T> function){
        if (ObjectUtils.isEmpty(trees)){
            return ;
        }
        trees.forEach(t->{
            int i = trees.indexOf(t);
            function.apply(t,parent,i);
            List<T> children = t.getChildren();
            __forEach(children,t,function);
        });
    }
}
